package com.xiaoye.app.service.impl;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xiaoye.app.common.MsgReturn;
import com.xiaoye.app.entity.Page;
import com.xiaoye.app.entity.User;
import com.xiaoye.app.mapper.UserMapper;
import com.xiaoye.app.service.UserService;
import com.xiaoye.app.util.PropertyCodeMsgUtil;
import com.xiaoye.app.util.StringUtil;

@Service("userService")
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;

	@Override
	public MsgReturn login(User user) throws SQLException {
		User returnUser = userMapper.login(user);
		if (returnUser == null) {
			return MsgReturn.ERROR_NODATA;
		}
		return MsgReturn.SUCCESS_MSG;
	}

	@Override
	public MsgReturn selectUserList(User user, Page page) throws SQLException {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("user", user);
		params.put("page", page);
		List<User> userList = userMapper.selectUserList(params);
		if (userList == null || userList.size() <= 0) {
			return MsgReturn.ERROR_NODATA;
		}
		int totalCount = userMapper.selectUserListCount(params);
		if (totalCount <= 0) {
			return MsgReturn.ERROR_NODATA;
		}
		return new MsgReturn(MsgReturn.SUCCESS, PropertyCodeMsgUtil.getPropertyValue(MsgReturn.SUCCESS), userList,
				totalCount);
	}

	@Override
	public MsgReturn selectUserListCount(User user, Page page) throws SQLException {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("user", user);
		params.put("page", page);
		int count = userMapper.selectUserListCount(params);
		if (count <= 0) {
			return MsgReturn.ERROR_NODATA;
		}
		return MsgReturn.SUCCESS_MSG;
	}

	@Override
	public MsgReturn deleteUser(User user) throws SQLException {
		if (user == null || StringUtil.INTEGER_IS_EMPTY(user.getId())) {
			return MsgReturn.ERROR_PARAM;
		}
		int delResult = userMapper.deleteUser(user);
		if (delResult <= 0) {
			return new MsgReturn(MsgReturn.DELETE_ERROR, PropertyCodeMsgUtil.getPropertyValue(MsgReturn.DELETE_ERROR));
		}
		return MsgReturn.SUCCESS_MSG;
	}

	@Override
	public MsgReturn updateUser(User user) throws SQLException {
		if (user == null) {
			return MsgReturn.ERROR_PARAM;
		}
		int updateResult = userMapper.updateUser(user);
		if (updateResult <= 0) {
			return MsgReturn.ERROR_NODATA;
		}
		return MsgReturn.SUCCESS_MSG;
	}

}
